/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.apache.jackrabbit.core.query.lucene;

import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.math.BigDecimal;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.Session;
import javax.jcr.Workspace;
import org.apache.jackrabbit.util.Text;
import org.apache.tika.metadata.MSOffice;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.sax.BodyContentHandler;


/**
 *
 * @author Administrator
 */
public class Import {

    public static void importing(File file) {
    }

    public static void importing(Workspace wk, URL... urls) throws Exception {
        Session session = wk.getSession();
        int n = 0;
        for (int i = 0; i < urls.length; i++) {
            final URL currentURL = urls[i];
            String path = urls[i].getPath();
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            final String host = urls[i].getHost();
            List folderNames = new ArrayList();
            folderNames.addAll(Arrays.asList(host.split("\\.")));
            Collections.reverse(folderNames);
            folderNames.addAll(Arrays.asList(path.split("/", 0)));
            final String fileName = URLDecoder.decode((String) folderNames.remove(folderNames.size() - 1), "UTF-8").replaceAll(":", "_");
            Node node = wk.getSession().getRootNode();
            for (Iterator fn = folderNames.iterator(); fn.hasNext();) {
                String name = URLDecoder.decode((String) fn.next(), "UTF-8");
                name = name.replaceAll(":", "_");
                if (name.length() == 0) {
                    continue;
                }
                if (!node.hasNode(name)) {
                    node.addNode(name, "nt:folder");
                    System.out.println("added name=" + name);
                }
                node = node.getNode(name);
                
            }
           System.out.println(fileName);
            if (!node.hasNode(fileName)) {
                System.out.println("importing..." + fileName);
                final PrintWriter fOut = new PrintWriter(System.out);
                final Node file = node.addNode(fileName, "nt:file");
                final Node resource = file.addNode("jcr:content", "nt:resource");
                final Exception[] ex = new Exception[1];
                Thread t = new Thread(new Runnable() {

                    public void run() {
                        try {
                            String info = fileName + " (" + host + ")";
                            URLConnection con = currentURL.openConnection();
                            InputStream in = con.getInputStream();
                           /* org.apache.tika.parser.Parser parser = new JackrabbitParser();
                            BodyContentHandler handler = new BodyContentHandler(System.out);


                             System.out.println("****");

                            
                            Metadata metadata = new Metadata();
                           try
                           {
                           
                            parser.parse(in, handler, metadata);

                             System.out.println("shit"+ metadata.get(Metadata.AUTHOR));

                             Node metaNode = file.getNode("jcr:content");
                             //metaNode.setProperty("w", BigDecimal.ONE);

                            for (Field f : Metadata.class.getFields()) {

                                f.setAccessible(true);
                                System.out.println("***"+f.getName()+ ":" + metadata.get(f.get(metadata).toString()));
                            }
                            } catch(Exception e) { e.printStackTrace();} 
                            */

                            try {
                                synchronized (fOut) {
                                    fOut.println("<script>dp.inform(0, '" + Text.encodeIllegalXMLCharacters(info) + "')</script>");
                                    fOut.flush();
                                }

                                resource.setProperty("jcr:data", in);
                                String mimeType = URLConnection.guessContentTypeFromName(fileName);
                                if (mimeType == null) {
                                    if (fileName.endsWith(".doc")) {
                                        mimeType = "application/msword";
                                    } else if (fileName.endsWith(".xls")) {
                                        mimeType = "application/vnd.ms-excel";
                                    } else if (fileName.endsWith(".ppt")) {
                                        mimeType = "application/mspowerpoint";
                                    } else {
                                        mimeType = "application/octet-stream";
                                    }
                                }
                                resource.setProperty("jcr:mimeType", mimeType);
                                Calendar lastModified = Calendar.getInstance();
                                lastModified.setTimeInMillis(con.getLastModified());
                                resource.setProperty("jcr:lastModified", lastModified);
                            } finally {
                                in.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ex[0] = e;
                        }
                    }
                });
                t.start();
                for (int s = 0; t.isAlive(); s++) {
                    Thread.sleep(100);
                    if (s % 10 == 0) {
                        synchronized (fOut) {
                            fOut.println("<script>pb.inform(" + n + ", '')</script>");
                            fOut.flush();
                        }
                    }
                }
                if (ex[0] == null) {
                    session.save();
                    n++;
                    synchronized (fOut) {
                        fOut.println("<script>pb.inform(" + n + ", '')</script>");
                        fOut.flush();
                    }

                } else {
                    session.refresh(false);
                }
            }
        }
        session.save();

    }
}
